package com.javer.util;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;

public abstract class IpAddressUtil {
	private static Log logger = LogFactory.getLog(IpAddressUtil.class);
	/**
	 * 根据IP地址查询地址接口
	 */
	static final String YouDaoUrl = "http://www.youdao.com/smartresult-xml/search.s?type=ip&q=";
	
	public static String getIpAddressXML(String ip) {
		StringBuilder sb = new StringBuilder();
		HttpURLConnection conn = null;
		BufferedReader br = null;
		
		try {
			URL ipUrl = new URL(YouDaoUrl + ip);
			conn = (HttpURLConnection)ipUrl.openConnection();
			br = new BufferedReader(new InputStreamReader(conn.getInputStream(), "GBK"));
			
			for (String line = br.readLine(); line != null; line = br.readLine()) {
				sb.append(line);
			}
		} 
		catch (Exception e) {
			logger.error(e);
		}
		finally {
			if (br != null) {
				try {
					br.close();
				} 
				catch (IOException e) {
					logger.error(e.getMessage(), e);
				}
			}
			if (conn != null) {
				conn.disconnect();
			}
		}
		return sb.toString();
	}
	
	public static String getIpAddressByIp(String ip) {
		String xml = getIpAddressXML(ip);
		int beg = xml.indexOf("<location>"), end = xml.indexOf("</location>");
		if (beg < 0 && beg >= end) {
			return "中国";
		}
		return xml.substring(beg + 10, end);
	}
	
	public static void main(String[] args) {
		System.out.println(IpAddressUtil.getIpAddressXML("59.58.2.171"));
		System.out.println(getIpAddressByIp("59.58.2.171"));
	}
}
